import mysql from 'mysql';
global.mysql=mysql;
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'vzo2ebs63k',
  database:'db1'
});
connection.connect(function(err) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }
  console.log('connected as id ' + connection.threadId);

});
global.connection=connection;
function insert(table,json){
    return new Promise((resolve,reject)=>{
        let keys=Object.keys(json).join(','),values=Object.values(json);
        connection.query(`INSERT INTO ${table} (${keys}) values (?)`,[values] ,function(err, result) {
            // console.log(err,'insert',result)
            if(result) resolve(result);
            else reject(err);
        })
    })

}
function deletez(table,where){
    return new Promise((resolve,reject)=>{
        connection.query(` DELETE FROM ${table} where ${where}`,function(err, result) {
            // console.log(err,'deletez',result)
            if(result) resolve(result);
            else reject(err);
        })
    })

}
function select(table,title){
    return new Promise((resolve,reject)=>{
        let column = title&&title.length>0?title.join(','):'*';
        connection.query(`select  ${column} from ${table}` ,function(err, result) {
            // console.log(err,'select',result)
            if(result) resolve(result);
            else reject(err);
        })
    })

}
function update(table,set,where){
    return new Promise((resolve,reject)=>{
        let temp = Object.keys(set).map(v=>{
            return v+'=?'
        });
        temp=temp.join(",");
        connection.query(`update ${table} set ${temp} where ${where}`,[...Object.values(set)] ,function(err, result) {
            // console.log(err,'update',result)
            if(result) resolve(result);
            else reject(err);
        })
    })

}
function mkTable(table,arr){
    return new Promise((resolve,reject)=>{
        let temp = arr.join(',')
        connection.query(`create table ${table} (${temp})` ,function(err, result) {
            // console.log(err,'table',result)
            if(result) resolve(result);
            else reject(err);
        })
    })

}
function mysqlz(str){
    return new Promise((resolve,reject)=>{
        connection.query(str ,function(err, result) {
            // console.log(err,'mysqlz',result);
            if(result) resolve(result);
            else reject(err);
        })
    })
}
async function hasTable(table){
    let res = await mysqlz('show tables')
    res = res.map(v=>{
        return Object.values(v)[0];
    })
    // console.log(res,table,9090,res.includes(table));
    return res.includes(table)
}


async function getModel(table,arr){
    let res = await mysqlz('select database()');
    if(!res[0]['database()']) return console.error("database未选，请先use database;");
    res =await hasTable(table);
    if(!res) {
        await mkTable(table,arr);
    }
    return {
        insert:json=>insert(table,json),
        deletez:where=>deletez(table,where),
        select:title=>select(table,title),
        update:(set,where)=>update(table,set,where),
        mysqlz:mysqlz
    }
}


const modelUp = await getModel('up',['id int(10) unique','uid int(30) unique','sex char(10)','face char(200)','name char(100) not null','fans char(30) not null'])
const modelFansLine = await getModel('fansline',['uid int(30)','time varchar(13)','fans char(30) not null','date char(30) ']);

export {
    modelUp,modelFansLine
}